<template>
  <div class="app-container clearfix">
    <div class="app-container-left">
      <!-- 左侧部门列表 -->
      <record-left
        :init-params="initParams"
        :search-params="searchKey"
        :department-all-list-data="departmentAllListData"
        @on-init="handleDepartmentNodeClick"></record-left>
    </div>
    <div class="app-container-right">
      <!-- 搜索 -->
      <record-search
        :init-params="initParams"
        :search-params="searchKey"
        :job-all-list-data="jobAllListData"
        @on-init="handleInitList"></record-search>
      <!-- 列表 -->
      <record-table
        :data="listData"
        :departmentData="departmentInfo"
        :search-params="searchKey"
        :total-count="totalCount"
        :list-loading="listLoading"
        @on-export="handleExport"
        @on-init="handleInitList"
        @on-delete="handleDeleteShow"
        @on-view="handleResumeShow"
        @on-edit="handleEditShow"></record-table>
      <!-- 编辑弹出框 -->
      <record-edit
        :visible.sync="editInfo.visible"
        :detail-data="editInfo.detailInfo"
        :department-all-list-data="departmentAllListData"
        :job-all-list-data="jobAllListData"
        :area-all-list-data="regionAllListData"
        :education-all-list-data="educationAllListData"
        :bank-all-list-data="bankAllListData"
        :political-all-list-data="politicalAllListData"
        :marry-all-list-data="marryAllListData"
        :nation-all-list-data="nationAllListData"
        @create="handleCreated"
        @update="handleUpdated"
        @on-export="handleEditExport"></record-edit>
      <!-- 删除弹出框 -->
      <record-delete
        :visible.sync="deleteInfo.visible"
        :detail-data="deleteInfo.detailInfo"
        @on-init="handleInitList"></record-delete>
      <!-- 简历弹出框 -->
      <record-resume
        :visible.sync="resumeInfo.visible"
        :detail-data="resumeInfo.detailInfo"
        @on-init="handleInitList"></record-resume>
    </div>
  </div>
</template>

<script>
  import { formatTimestamp } from '@/utils/utils'
  import { getRecordListAPI, exportRecordAPI } from '@/api/employee/record'
  import { fileDownloadAPI } from '@/api/common'
  import { RecordSearch, RecordTable, RecordEdit, RecordDelete, RecordResume, RecordLeft } from './components'
  import commonMixins from '@/mixins/common'
  import treeAllListData from '@/mixins/treeAllListData'
  import request from '@/utils/request'

  export default {
    name: 'RecordList',
    mixins: [commonMixins, treeAllListData],
    components: {
      RecordSearch,
      RecordTable,
      RecordEdit,
      RecordDelete,
      RecordResume,
      RecordLeft
    },
    data() {
      return {
        initParams: { // 初始化参数
          pageNum: 1, // 当前页数
          pageSize: 10, // 每页个数
          sort: '', // 排序
          deptId: '', // 部门ID
          name: '', // 名称
          status: 0, // 状态
          postIds: [], // 职务
          payBusinessInsurance: '', // 是否缴纳商业险
          salaryRange: '', // 工资范围
          entrySelectedDate: [], // 入职日期
          dimissionSelectedDate: [] // 离职日期
        },
        searchKey: {}, // 搜索参数
        editInfo: { // 编辑弹出框
          visible: false, // 是否显示模态框
          detailInfo: {}
        },
        deleteInfo: { // 删除弹出框
          visible: false, // 是否显示模态框
          detailInfo: {}
        },
        resumeInfo: { // 简历弹出框
          visible: false, // 是否显示模态框
          detailInfo: {}
        },
        totalCount: 0, // 分页用的列表总条数
        listLoading: false,
        departmentInfo: {}, // 部门详情信息
        listData: [] // 列表数据
      }
    },
    props: {},
    computed: {},
    methods: {
      handleEditShow(data = {}) { // 编辑－显示弹出框
        this.editInfo.visible = true
        this.editInfo.detailInfo = data
      },
      handleDeleteShow(data = {}) { // 删除－显示弹出框
        this.deleteInfo.visible = true
        this.deleteInfo.detailInfo = data
      },
      handleResumeShow(data = {}) { // 简历－显示弹出框
        this.resumeInfo.visible = true
        this.resumeInfo.detailInfo = {}
        request({
          url: '/hr/employee/' + data.id,
          method: 'get',
          params: {}
        }).then(response => {

          if (response.code != '200') {
            this.msgError('后台请求出错，原因是' + response.msg)
            return
          }
          data = response.data
          this.resumeInfo.detailInfo = data
        })

      },
      handleCreated() { // 添加成功
        this.searchKey.pageNum = 1
        this.getListData()
      },
      handleUpdated() { // 编辑成功
        this.getListData()
      },
      handleInitList(params = {}) { // 初始化列表
        this.searchKey = {
          ...this.searchKey,
          ...params
        }
        this.getListData()
      },
      handleDepartmentNodeClick(data) { // 左侧部门点击
        this.searchKey = {
          ...this.searchKey,
          ...data.searchKey
        }
        this.departmentInfo = data.departmentInfo
        this.getListData()
      },
      async handleEditExport(data) { // 编辑页-附件导出
        try {
          let response = await fileDownloadAPI({
            fileName: data.fileName
          })
          this.downloadFile(response)
        } catch (error) {
          this.$notify.error({
            title: '错误',
            message: error.message || '导出失败!'
          })
        }
      },
      handleExport(tableSelectedData) { // 导出按钮操作

        let { searchKey } = this

        let query = {
          ...searchKey,
          ...{
            postIds: this.searchKey.postIds.join(','),
            entrySelectedDate: '',
            dimissionSelectedDate: '',
            onboardingDate: this.searchKey.entrySelectedDate[0],
            onboardingDate2: this.searchKey.entrySelectedDate[1],
            leaveDate: this.searchKey.dimissionSelectedDate[0],
            leaveDate2: this.searchKey.dimissionSelectedDate[1]
          }
        }

        let ids = []
        if (tableSelectedData.length) {
          for (let i = 0; i < tableSelectedData.length; i++) {
            ids.push(tableSelectedData[i].id)
          }
          query = { ids: ids.join(',') }
        }

        this.$confirm('是否导出所选数据?如未选择将导出查询条件所有数据！', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          try {
            let response = await exportRecordAPI(query)
            this.downloadFile(response)
          } catch (error) {
            // console.log(error)
            this.$notify.error({
              title: '错误',
              message: error.message || '操作失败！'
            })
          }
        }).catch(() => {
        })
      },
      async getListData() { // 获取列表数据
        try {
          let { searchKey } = this
          this.listLoading = true
          let response = await getRecordListAPI({
            ...searchKey,
            ...{
              postIds: this.searchKey.postIds.join(','),
              entrySelectedDate: '',
              dimissionSelectedDate: '',
              onboardingDate: this.searchKey.entrySelectedDate[0],
              onboardingDate2: this.searchKey.entrySelectedDate[1],
              leaveDate: this.searchKey.dimissionSelectedDate[0],
              leaveDate2: this.searchKey.dimissionSelectedDate[1]
            }
          })
          let result = response
          if (+result.code === 200) {
            let resultData = result.rows || []
            this.listData = resultData.map((item, index) => {
              console.log(item.contractEndDate)
              if (item.contractEndDate) {
                let contractEndDate = formatTimestamp(item.contractEndDate) // 合同到期时间戳
                let nowDate = Date.parse(new Date()) // 当前时间时间戳
                let expireDate = Date.parse(new Date()) + 3600 * 1000 * 24 * 30 // 一月后时间戳
                if (contractEndDate > expireDate) { // 1、合同正常 2、将要到期 3、合同过期
                  item.contractSatatus = '1'
                } else if (contractEndDate <= nowDate) {
                  item.contractSatatus = '3'
                } else {
                  item.contractSatatus = '2'
                }
              } else {
                item.contractSatatus = '1'
              }
              return item
            })
            this.totalCount = result.total || 0
          } else {
            this.$notify.error({
              title: '错误',
              message: result.msg || '获取列表失败！'
            })
          }
        } catch (error) {
          // console.log(error)
          this.$notify.error({
            title: '错误',
            message: error.message || '获取列表失败!'
          })
        } finally {
          this.listLoading = false
        }
      },
      async initBeforeRoute(obj, to, from) { // 初始化页面
        let { status = '0' } = to.query
        obj.searchKey.status = +status
        obj.initData()
      },
      async initData() { // 初始化数据
        this.getListData()
        this.getJobAllListData()
        this.getRegionAllListData()
        this.getEducationAllListData()
        this.getBankAllListData()
        this.getPoliticalAllListData()
        this.getMarryAllListData()
        this.getNationAllListData()
        await this.getDepartmentAllListData()
        this.departmentInfo = this.departmentAllListData[0]
      }
    },
    watch: {
      initParams: {
        handler: function(newVal, oldVal) {
          if (JSON.stringify(newVal) !== JSON.stringify(this.searchKey)) {
            this.searchKey = JSON.parse(JSON.stringify(newVal))
          }
        },
        deep: true,
        immediate: true
      }
    },
    created() {
    },
    mounted() {
    },
    beforeRouteEnter(to, from, next) {
      // console.log(to)
      // console.log(from)
      next(vm => {
        vm.initBeforeRoute(vm, to, from)
      })
    },
    beforeRouteUpdate(to, from, next) {
      // console.log(to)
      // console.log(from)
      this.initBeforeRoute(this, to, from)
      next()
    }
  }
</script>

<style lang="scss" scoped>
  .app-container {
    &-left {
      width: 220px;
      float: left;
    }

    &-right {
      margin-left: 250px;
    }
  }
</style>
